import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: null,
    refreshToken: null
  }),
  
  getters: {
    // 获取用户ID
    userId: (state) => state.userInfo?.id,
    
    // 获取用户名
    userName: (state) => state.userInfo?.userName,
    
    // 获取用户邮箱
    userEmail: (state) => state.userInfo?.email,
    
    // 获取用户手机号
    userPhone: (state) => state.userInfo?.phoneNumber,
    
    // 获取用户头像
    userAvatar: (state) => state.userInfo?.avatarUrl,
    
    // 检查是否已登录
    isLoggedIn: (state) => !!state.token && !!state.userInfo,
    
    // 获取用户状态
    userStatus: (state) => state.userInfo?.status || 'unknown'
  },
  
  actions: {
    // 设置用户信息
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },
    
    // 设置token
    setToken(token) {
      this.token = token
    },
    
    // 设置refreshToken
    setRefreshToken(refreshToken) {
      this.refreshToken = refreshToken
    },
    
    // 设置完整的认证信息
    setAuth(authData) {
      if (authData.accessToken) {
        this.token = authData.accessToken
      }
      if (authData.refreshToken) {
        this.refreshToken = authData.refreshToken
      }
      if (authData.user) {
        this.userInfo = authData.user
      }
    },
    
    // 更新用户信息
    updateUserInfo(updates) {
      if (this.userInfo) {
        this.userInfo = { ...this.userInfo, ...updates }
      }
    },
    
    // 清除用户信息
    clearUserInfo() {
      this.userInfo = null
      this.token = null
      this.refreshToken = null
    },
    
    // 登出
    logout() {
      this.clearUserInfo()
    }
  }
})